package com.zhj.helloframework.mvc.render.impl;

import com.zhj.helloframework.mvc.RequestProcessorChain;
import com.zhj.helloframework.mvc.render.ResultRender;
import com.zhj.helloframework.mvc.type.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author: zhj
 * @Description: 视图渲染器
 * @Date: 2021/11/16 15:59
 * @Version: 1.0
 */
public class ViewResultRender implements ResultRender {

    // jsp页面所在的根目录
    public static final String VIEW_PATH = "/templates/";

    private ModelAndView modelAndView;

    public ViewResultRender(Object mav) {
        if (mav instanceof ModelAndView) {
            // 1.如果入参类型是ModelAndView，则直接赋值给成员变量
            this.modelAndView = (ModelAndView) mav;
        } else if (mav instanceof String) {
            // 2.如果入参类型是String，则是视图，需要包装后才能赋值给成员变量
            this.modelAndView = new ModelAndView().setView((String) mav);
        } else {
            // 3.针对其他情况直接抛出异常
            throw new RuntimeException("illegal request result type");
        }
    }

    @Override
    public void render(RequestProcessorChain requestProcessorChain) throws Exception {
        // 获取当前http请求的request和response
        HttpServletRequest request = requestProcessorChain.getRequest();
        HttpServletResponse response = requestProcessorChain.getResponse();
        // 获取要访问的jsp页面的路径
        String path = modelAndView.getView();
        // 获取需要转发的数据
        Map<String, Object> model = modelAndView.getModel();
        // 把数据设置进request
        for (Map.Entry<String, Object> entry : model.entrySet()) {
            request.setAttribute(entry.getKey(), entry.getValue());
        }
        // 请求转发
        request.getRequestDispatcher(VIEW_PATH + path).forward(request,response);
    }
}
